package com.jpush.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Component
public class WebFluxUserRequestInfoFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest newRequest = null;
        try {
            newRequest = exchange.getRequest().mutate()
                    .header("X-UserInfo",URLEncoder.encode("xiaosu 冬马 gateway 的数据","UTF-8"))
                    .build();
        } catch (UnsupportedEncodingException e) {
            return Mono.error(new RuntimeException("URLEncoder.encode UserRequestInfo 失败"));
        }
        return chain.filter(exchange.mutate().request(newRequest).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
